#!/bin/bash

clear
echo
echo "Welcome!"
echo
echo "This is the Android Central Installer!"
echo "You can also check for updates here :)"
echo
echo "Press ENTER to continue"
read line

git --version

if [ "$?" = "1" ]
then
	clear
	echo "ERROR!"
	echo "The GIT-CORE is not found, do you want to install it (Ubuntu)?"
	echo "It makes updating a lot easier!"
	echo	
	echo -n "Enter option [Y/n] : "
	read opt
	if [ "$opt" = "n" ]
	then
		clear
		echo "Well, OK then. Press enter and go to the topic to download the full version."
		read line
		wget -q http://forum.xda-developers.com/showthread.php?t=1491689
	else
		sudo apt-get install git-core
	fi
fi

clear
echo
echo "Git-Test passed :)"
echo "Press Enter!"
read line


MyCommand=${0##*/}
Dir=${0%%/"$MyCommand"}
ScriptDir=$(cd $Dir && pwd)
UpdDir=$ScriptDir
ScriptCommand="AC"

if ! [ -f ~/bin/AC ]
then
	if ! [ -f $UpdDir/$ScriptCommand ]
	then
		clear
		echo "Press ENTER to install..."
		echo	
		echo "If you already installed and want to check for updates,"
		echo "Then place this script inside the AndroidCentral directory."
		echo "And enter X to restart when you are done."
		read opt
		if [ "$opt" = "x" ] || [ "$opt" = "X" ]
		then
			$ScriptDir/$MyCommand
			exit
		else
			git clone git://github.com/mDroidd/AndroidCentral.git ~/AndroidCentral
			ln -s ~/AndroidCentral ~/AC
			~/AndroidCentral/$ScriptCommand
			exit
		fi
	fi
else
	File=$(tail -1 ~/bin/$ScriptCommand)
	Dir=${File%%/$ScriptCommand}
	if [ "$?" = "1" ]
	then
		clear
		echo "Whoops, ERROR!, could you please scroll back and PM me the error?"
		echo "Press ENTER to continue..."
		read line
		exit
	fi
fi


if [ -f $UpdDir/changelog ]
then
	rm $UpdDir/changelog
fi

wget -q http://dl.dropbox.com/u/61466577/changelog

Version=$(head -1 $UpdDir/changelog)
CVersion=$(tail -1 $Dir/$ScriptCommand)
Changes=$(tail -11 $UpdDir/changelog)

if [[ $Version > $CVersion ]]
then
	clear
	echo "Update found :)"
	echo "Changes: "
	echo
	tail -11 "$UpdDir/changelog"
	echo
	echo "Press ENTER to install!"
	read line

	git pull git://github.com/mDroidd/AndroidCentral.git $UpdDir
	if [ "$?" = "128" ]
	then
		clear
		echo "Warning! The directory containing AndroidCentral will now be deleted."
		echo "If you were building from source, or if you have data in it: BACK IT UP!"
		echo
		echo "Everything inside $UpdDir will be deleted!"
		echo
		echo "Press ENTER to continue"
		read line
		echo "Sorry for the triple warning"
		echo "Everything inside $UpdDir will be deleted!"
		read line
		rm -rf $UpdDir/*
		rm -rf $UpdDir/.*
		git clone git://github.com/mDroidd/AndroidCentral.git $UpdDir
	fi
else
	clear
	echo
	echo "Nope, no updates found..."
	echo "Latest changes:"
	tail -11 $UpdDir/changelog
fi
read line
